package com.it.travel.service.admin.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.travel.common.ConstEnum;
import com.it.travel.dao.UserMapper;
import com.it.travel.dao.UserRoleMapper;
import com.it.travel.pojo.User;
import com.it.travel.pojo.UserRole;
import com.it.travel.service.admin.AdminUserService;
import com.it.travel.vo.Params.PageParams;
import com.it.travel.vo.Params.admin.AdminUserParams;
import com.it.travel.vo.Params.admin.AdminUserUpdateParams;
import com.it.travel.vo.Result;
import com.it.travel.vo.admin.AdminUserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class AdminUserServiceImpl implements AdminUserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;

    //    @Resource
    @Override
    public Result<?> getUserInfoPage(PageParams pageParams) {
        String keywords = pageParams.getKeywords();
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(keywords)) {
            wrapper.like(User::getRealname, keywords);
        }
        Integer index = pageParams.getIndex();
        Page<User> page = new Page<>(index, pageParams.getSize());
        Page<User> userPage = userMapper.selectPage(page, wrapper);
        List<User> userList = userPage.getRecords();
        List<AdminUserVO> list = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HashMap<String, Object> map = new HashMap<>();
        for (User user : userList) {
            AdminUserVO adminUserVO = new AdminUserVO();
            String roleName = userMapper.queryRoleNameByUserName(user.getUsername());
            adminUserVO.setIdentity(roleName);
            BeanUtils.copyProperties(user, adminUserVO);
            Date date = new Date(user.getCreateTime());
            String format = simpleDateFormat.format(date);
            adminUserVO.setFormatTime(format);
            list.add(adminUserVO);
        }
        map.put("total", userPage.getTotal());
        map.put("userList", list);
        return Result.success(map, "获取用户数据成功");

    }

    @Override
    public Result<?> save(AdminUserParams adminUserParams) {
        String username = adminUserParams.getUsername();
        User username1 = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (username1 != null) {
            return Result.error(null, "用户名重复");
        }
        User user = new User();
        BeanUtils.copyProperties(adminUserParams, user);
        user.setCreateTime(System.currentTimeMillis());
        user.setUpdateTime(System.currentTimeMillis());
        String password = SecureUtil.md5(ConstEnum.SALT.getStr() + ConstEnum.DEFAULT_PASSWORD.getStr());
        user.setPassword(password);
        int i = userMapper.insert(user);
        if (i > 0) {
            return Result.success(null, "添加用户成功");
        } else {
            return Result.success(null, "添加用户失败");
        }
    }

    /**
     * @param id 用户id
     * @return
     */
    @Override
    @Transactional
    public Result<?> delete(Integer id) {  //由于没有外键，所以一切级联操作都在应用层面上解决
        int i1 = userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id", id));
        int i = userMapper.deleteById(id);
        if (i > 0 && i1 > 0) {
            return Result.success(null, "删除成功");
        } else {
            return Result.error(null, "删除失败");
        }

    }

    @Override
    public Result<?> update(AdminUserUpdateParams adminUserUpdateParams) {
        String SALT = ConstEnum.SALT.getStr();// 加密盐
        String password = adminUserUpdateParams.getPassword();
        if (password != null) {  // 说明修改了密码
            password = SecureUtil.md5(SALT + adminUserUpdateParams.getPassword());
        } else {  // 没修改密码
            User user = userMapper.selectById(adminUserUpdateParams.getId());
            password = user.getPassword();
        }
        User user = new User();
        BeanUtils.copyProperties(adminUserUpdateParams, user);
        user.setPassword(password);
        user.setUpdateTime(System.currentTimeMillis());
        int i = userMapper.updateById(user);
        if (i > 0) {
            return Result.success(null, "修改用户信息成功");
        }
        return Result.error(null, "修改用户信息失败");
    }

    @Transactional
    @Override
    public Result<?> deletebatch(List<Integer> ids) { //由于没有外键，所以一切级联操作都在应用层面上解决
        Integer count = 0;
        for (Integer id : ids) {
            int id1 = userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id", id));
            count++;
        }
        int i = userMapper.deleteBatchIds(ids);
        if (i > 0 && count == ids.size()) {
            return Result.success(null, "批量删除成功");
        }
        return Result.error(null, "批量删除失败");
    }


}
